use diesel::prelude::*;
use diesel::MysqlConnection;

use super::model::*;
use crate::database::{crud, schema::user, DbError};
use crate::{db_create, db_delete, db_read_by_field, db_read_count_from_offset, db_update};

db_create!(user, User, NewUser, create);
db_read_by_field!(user, User, read_by_username, username, String);
db_read_count_from_offset!(user, User, read_count_from_offset);
db_update!(user, NewUser, update);
db_delete!(user, delete);

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        database::{
            self, establish_connection,
            table::{category::model::NewCategory, tag::model::NewTag},
        },
        db_read, test_db_create, test_db_delete, test_db_update,
    };
    use diesel::Connection;

    db_read!(user, User, read);

    fn insert_test_data(conn: &mut MysqlConnection) -> (i32, i32, i32) {
        let cid = database::table::category::crud::create(
            conn,
            NewCategory {
                name: "CATE",
                desc: "DESC",
                cover: "COVER",
                slug: "LINK",
            },
        )
        .unwrap();
        let tid = database::table::tag::crud::create(
            conn,
            NewTag {
                name: "TAG1",
                desc: "DESC1",
                avatar: "AVATAR1",
                slug: "LINK1",
                cid,
            },
        )
        .unwrap();
        let uid1 = create(
            conn,
            NewUser {
                username: "USER1",
                password: "PASSWORD1",
                tid,
            },
        )
        .unwrap();
        let uid2 = create(
            conn,
            NewUser {
                username: "USER2",
                password: "PASSWORD2",
                tid,
            },
        )
        .unwrap();
        (uid1, uid2, tid)
    }

    test_db_create!();
    test_db_update!(username, "NEW_USER".to_string());
    test_db_delete!();
}
